﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StableDiffusionTools.Animation
{
    public static class AnimationUtil
    {
        public static Frame[] GetFrames(Image image)
        {
            Frame[] result = null;
            Guid[] guids = image.FrameDimensionsList;
            if(guids.Length != 0)
            {
                FrameDimension frameDimension = new FrameDimension(guids[0]);
                int frameCount = image.GetFrameCount(frameDimension);
                if(frameCount > 1)
                {
                    result = new Frame[frameCount];
                    byte[] times = null;
                    try
                    {
                        times = image.GetPropertyItem(0x5100)?.Value; //PropertyTagFrameDelay
                    }
                    catch (Exception) { /*Ignored*/ }

                    for (int i = 0; i < frameCount; i++)
                    {
                        image.SelectActiveFrame(frameDimension, i);
                        int duration = 0;
                        if(times != null && i < times.Length)
                            duration = BitConverter.ToInt32(times, 4 * i) * 10;

                        result[i] = new Frame(duration, new Bitmap(image));
                    }
                }
            }

            if (result == null) result = new Frame[] { new Frame(0, new Bitmap(image)) };

            return result;
        }

        public static IntPtr[] GetHBitmaps(Frame[] frames)
        {
            IntPtr[] result = new IntPtr[frames.Length];
            for (int i = 0; i < frames.Length; i++)
            {
                result[i] = frames[i].GetHbitmap();
            }
            return result;
        }

        public static int GetPeriodFromFPS(int fps)
        {
            return 1000 / fps;
        }

        public static bool IsValidFPS(int fps)
        {
            return fps > 0;
        }
    }
}
